<?php

namespace app\portal\controller;

use app\admin\model\Question;
use app\common\controller\PortalBase;
use think\Exception;
use think\Request;
use think\Config;

class Study extends PortalBase {
  protected $modelStudy, $modelQuestion;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->modelStudy = new \app\admin\model\Study();
    $this->modelQuestion = new Question();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {

  }


  public function view() {
    $questions = $this->modelQuestion
      ->where('disable', 0)
      ->column('id,content,type,answers,right');

    $questionIDs = array_keys($questions);
    $nowTimestamp = time();
    $cursorMax = count($questions);//最大游标
    $cursors = json_encode(range(1, $cursorMax));

    $styduAnswers = $this->modelStudy->find($this->uid);
    $cursor = 0;
    $signs = $answers = [];
    if ($styduAnswers) {
      $signs = $styduAnswers['signs'];
      $answers = $styduAnswers['answers'];
      $cursor = $styduAnswers['cursor'];
    }

    cmf_log('开始顺序学习', 0, date('Y-m-d H:i'));
    $returnData = [
      'cursorMax'    => $cursorMax,
      'cursor'       => $cursor,
      'cursors'      => $cursors,
      'answers'      => $answers,
      'signs'        => $signs,
      'nowTime'      => date('H:i:s', $nowTimestamp),
      'nowTimestamp' => $nowTimestamp,
      'questionIDs'  => json_encode($questionIDs),
      'questions'    => json_encode($questions),
    ];
    if (!request()->isAjax()) {
      return view('', $returnData);
    }
    $this->result($returnData, 1);

  }

  public function view_pre() {
    $questions = $this->modelQuestion
      ->where('disable', 0)
      ->column('id,type,answers,right');

    $questionIDs = array_keys($questions);
    $nowTimestamp = time();
    $cursorMax = count($questions);//最大游标

    $questionTypeCount = [];
    foreach ($questions as $q) {
      $questionTypeCount[ $q['type'] ] += 1;
    }
    //
    $studyAnswers = $this->modelStudy->find($this->uid);
    $cursor = 0;
    $signs = $answers = [];
    if ($studyAnswers) {
      $signs = $studyAnswers['signs'];
      $cursor = $studyAnswers['cursor'];
    }

    $returnData = [
      'questionTypeCount' => $questionTypeCount,
      'qType'             => config('question')['type'],
      'cursorMax'         => $cursorMax,
      'cursor'            => $cursor,
      'signs'             => $signs,
      'nowTime'           => date('H:i:s', $nowTimestamp),
      'nowTimestamp'      => $nowTimestamp,
      'questionIDs'       => json_encode($questionIDs),
    ];
    if (!request()->isAjax()) {
      return view('', $returnData);
    }
    $this->result($returnData, 1);

  }

  public function getPaperQuestions() {
    $paperId = input('paper_id', 0);
    $cursor = input('cursor/d', 0);
    $paper = ($paperId > 0) ? $this->model->find($paperId) : NULL;
    if (!$paper)
      $this->error(lang('paper empty'));
    $map = [
      'uid'      => $this->uid,
      'paper_id' => $paperId,
      'status'   => 0,
    ];
    $testAnswer = $this->modelTestAnswer->where($map)->find();
    //返回所有问题的数据
    $paperQuestionIDs = json_decode($paper['questions'], TRUE);
    $paperQuestions = $this->modelQuestion->where('id', 'in', $paperQuestionIDs)->column('content,answers', 'id');
    //返回所有问题的答案
    $paperAnswers = json_decode($testAnswer['answers'], TRUE);
    //返回所有的标记
    $paperSign = json_decode($testAnswer['sign'], TRUE);
    $active = -1;
    if ($paperAnswers) {
      $active = $paperAnswers[ $cursor ];
    } else {
      $paperAnswers = [];
    }
    //返回数据
    $data = [
      'question'         => $paperQuestions[0],
      'paperQuestionIDs' => $paperQuestionIDs,
      'paperQuestions'   => $paperQuestions,
      'paperSign'        => $paperSign ? $paperSign : [],
      'active'           => $active,
      'paperAnswers'     => $paperAnswers,
      'examFinish'       => $testAnswer['status'],
    ];
    $this->result($data, 1);
  }

  public function doAnswer() {
    $cursor = input('cursor/d', 0);
    $answer = input('answer/d', 0);
    $sign = input('sign/d', 0);

    $studyAnswer = $this->modelStudy->find($this->uid);
    $answers = json_decode($studyAnswer['answers'], TRUE);
    $signs = json_decode($studyAnswer['signs'], TRUE);
    $answers[ $cursor ] = $answer;
    $signs[ $cursor ] = $sign;
    $data = [
      'answers' => json_encode($answers),
      'signs'   => json_encode($signs),
      'cursor'  => $cursor,
      'uid'     => $this->uid,
    ];
    try {
      if (!$studyAnswer) {
        $r = $this->modelStudy->save($data);
      } else {
        $r = $this->modelStudy->save($data, ['uid' => $this->uid]);
      }

    } catch (Exception $e) {
      $this->error(lang('error') . $e->getMessage());
    }
    if ($r === FALSE) $this->error(lang('error') . $this->modelTestAnswer->getError());
    $this->success();
  }


  public function clearAnswer() {
    $r = FALSE;
    try {
      $r = $this->modelStudy->where(['uid' => $this->uid])->delete();
    } catch (Exception $e) {
      $this->error(lang('error') . $e->getMessage());
    }
    if ($r !== FALSE) {
      $this->success();
    }
    $this->error(lang('error') . $this->modelStudy->getError());
  }

}